<template>
  <el-form label-width="80px" :model="supInfo" :rules="rules" ref="supInfo">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input v-model="supInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select  placeholder="请选择活动区域" v-model="supInfo.tmId">
        <el-option v-for="trademark in trademarkList"  :key="trademark.id"
                   :value="trademark.id"
                   :label="trademark.tmName" ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" :rows="4"
                placeholder="请输入内容" v-model="supInfo.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片" prop="spuImageList">
      <!--
          action : 图片的上传接口
          list-type：图片列表的展示形式
          on-preview：点击文件列表中已上传的文件时的钩子
          on-remove：文件列表移除文件时的钩子
          before-upload :上传文件之前的钩子
          on-success: 当上传图片的接口调用成功之后的回调
      -->
      <el-upload
        action="/dev-api/admin/product/fileUpload"
        list-type="picture-card"
        :file-list="supInfo.spuImageList"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select :placeholder="placeholder" v-model="attr_id_name">
        <el-option v-for="baseSaleAttr in unUsedBaseSaleAttrList"
                   :key="baseSaleAttr.id"
                   :value="`${baseSaleAttr.name}-${baseSaleAttr.id}`"
                   :label="baseSaleAttr.name"></el-option>
      </el-select>
      <el-button type="primary"  @click="addAttr"
                 icon="el-icon-circle-plus-outline">添加销售属性</el-button>
      <el-table style="margin: 20px 0" border :data="supInfo.spuSaleAttrList">
        <el-table-column align="center" label="序号" type="index" width="80"></el-table-column>
        <el-table-column align="center" label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column align="center" label="属性值列表">
          <template slot-scope="{row,$index}">
            <el-tag
              :key="tag.id"
              v-for="(tag,index) in row.spuSaleAttrValueList"
              closable
              :disable-transitions="false"
              @close="handleClose(row,index)">
              {{tag.saleAttrValueName}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.inputVisible"
              v-model="row.inputValue"
              :ref="`saveTagInput${$index}`"
              size="small"
              @keyup.enter.native="handleInputConfirm(row,$index)"
              @blur="handleInputConfirm(row,$index)"></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(row,$index)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{row,$index}">
            <HintButton title="删除SPU" type="danger" @click="supInfo.spuSaleAttrList.splice($index,1)"
                        icon="el-icon-delete" size="mini" ></HintButton>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="addOrUpdate" :loading="loading">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
    export default {
      name: "spu_addOrUpdate",
      data() {
        //图片的自定义校验器
        let spuImageListVFn = (rule, value, callback) => {
          if(value.length >=1){
            callback()
          }else{
            callback("必须指定一张图片")
          }
        }

        //销售属性的自定义校验器
        let spuSaleAttrListVFn = (rule, value, callback) => {

          //item : 一个个销售属性！！！
          //flag: 如果flag为true  代表肯定有一个销售属性 且 它有值
          let flag = value.some(item => item.spuSaleAttrValueList.length > 0)
          if(flag){
            callback()
          }else{
            callback("必须指定一个销售属性")
          }
        }

        return {
          //品牌数据
          trademarkList:[],
          //销售属性数据
          baseSaleAttrList:[],
          //spu详情
          supInfo:{
            id: "",
            spuName: "",
            description: "",
            category3Id: "",  //category3Id 在新增的时候 是没有表单元素对应的！ 录不到数据的
            tmId:"",
            spuSaleAttrList: [],
            spuImageList: []
          },
          //图片上传相关
          dialogImageUrl: '',
          dialogVisible: false,

          //基本销售属性的id 和 name
          attr_id_name:"",

          loading:false,

          //表单验证
          rules: {
            spuName: [{ required: true, message: '请输入SPU名称', trigger: 'change' }],
            tmId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
            description: [{ required: true, message: '请输入SPU描述信息', trigger: 'change' }],
            spuImageList:{ validator: spuImageListVFn, trigger: 'blur' },
            spuSaleAttrList:{ validator: spuSaleAttrListVFn, trigger: 'blur' }
          }
        };
      },
      computed:{
        // 未使用过的基础的销售属性
        unUsedBaseSaleAttrList(){
            //baseSaleAttrList : 总的销售属性
            const {baseSaleAttrList,supInfo:{spuSaleAttrList}} = this;
            const result =  baseSaleAttrList.filter((baseSaleAttr)=>{
                //flag:true  代表 baseSaleAttr的id 在spuSaleAttrList中出现过 要抛弃掉
                //flag:false  代表 baseSaleAttr的id 在整个spuSaleAttrList中都没出现过 要保留
                let flag = spuSaleAttrList.some((spuSaleAttr)=>{
                  // 查看当前baseSaleAttr的id 是不是在spuSaleAttrList中出现过
                  return +baseSaleAttr.id === +spuSaleAttr.baseSaleAttrId
                })


                //返回true ： 将当前的baseSaleAttr塞到 result中
                //返回false ： 将当前的baseSaleAttr抛弃掉
                return !flag;
            })

            return result
        },
        // 未使用过的基础的销售属性的下拉列表的提示文案
        placeholder(){
          return this.unUsedBaseSaleAttrList.length <=0 ?
              "没有啦" :
              `还剩${this.unUsedBaseSaleAttrList.length}个可以选择`;
        }
      },
      methods: {
        //清空表单数据
        clearForm(){
          this.trademarkList=[];
          this.baseSaleAttrList=[];
          this.supInfo={
            id: "",
              spuName: "",
              description: "",
              category3Id: "",  //category3Id 在新增的时候 是没有表单元素对应的！ 录不到数据的
              tmId:"",
              spuSaleAttrList: [],
              spuImageList: []
          };
          this.dialogImageUrl='';
          this.dialogVisible= false;
          this.attr_id_name="";
          this.loading=false
        },

        //发送请求修改spu
        async addOrUpdate(){
          this.$refs.supInfo.validate(async (valid) => {
            //valid:true 代表当前表单项全部通过验证
            if(valid){
              try {
                this.supInfo.spuImageList = this.supInfo.spuImageList.map(image=>({
                  imgName:image.name,
                  imgUrl:image.url
                }))

                this.loading = true
                await this.$API.spu.addOrUpdate(this.supInfo)

                //给成功的提醒
                this.$message(`${this.supInfo.id?"修改":"新增"}spu信息成功`)

                //当前修改界面要关闭 显示列表界面
                this.$parent.$parent.showListFn()

                //列表界面要刷新
                //this.$parent.$parent.getSpuList(1)
                this.$emit("success")

              }catch (e) {

              }finally {
                this.loading = false
              }
            }
          })
        },


        //获取数据 为新增
        async initDataForAdd(category3Id){

          //清除残留的检验信息
          this.$refs.supInfo.clearValidate()

          this.supInfo.category3Id =category3Id;
          const {data:trademarkList} = await this.$API.trademark.getTrademarkList();
          const {data:baseSaleAttrList} = await this.$API.spu.getBaseSaleAttrList();
          this.trademarkList = trademarkList;
          this.baseSaleAttrList = baseSaleAttrList;
        },
        //获取数据 为编辑
        async initData(spuid){
            //清除残留的检验信息
            this.$refs.supInfo.clearValidate()

            //发请求 获取trademarkList spuAttrList
            const {data:trademarkList} = await this.$API.trademark.getTrademarkList();
            const {data:baseSaleAttrList} = await this.$API.spu.getBaseSaleAttrList();
            const {data:supInfo} = await this.$API.spu.getSpuInfoById(spuid);
            let {data:spuImageList} = await this.$API.spu.getSpuImageList(spuid);
            this.trademarkList = trademarkList;
            this.baseSaleAttrList = baseSaleAttrList;
            this.supInfo = supInfo;


          /*{
              id: 14735
              imgName: "brand_05.png"
              imgUrl: "http://182.92.128.115:8080/group1/M00/00/C0/rBFUDF_aKk2Aa89lAAAH8DFDLcM547.png"
              spuId: 210
              status: "success"
              uid: 1609905079759
            }  */
          spuImageList = spuImageList.map(image=>({
              name:image.imgName,
              url:image.imgUrl
          }))

          this.supInfo.spuImageList = spuImageList;
        },
        //关闭新增&修改界面 显示列表界面
        cancel(){
          this.$parent.$parent.showListFn()
        },

        //图片上传相关
        handleRemove(file, fileList) {
          //当图片删除成功之后 将删除成功之后的图片列表同步给spuImageList
          this.supInfo.spuImageList = fileList;
        },
        handleAvatarSuccess(response, file, fileList){
          //当图片添加成功之后 将添加成功之后的图片列表同步给spuImageList
          this.supInfo.spuImageList = fileList;
        },
        handlePictureCardPreview(file) {
          //file : 点击的那张图
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024  < 60;

          if (!isJPG) {
            this.$message.error({
              message:'上传头像图片只能是 JPG 格式!',
              duration:1000
            });
          }
          if (!isLt2M) {
            //清除上一个提示
            this.$message.closeAll();
            this.$message.error({
              message:"上传头像图片大小不能超过 30kb!",
              duration:1000
            });
          }
          return isJPG && isLt2M;
        },

        //新增一个销售属性
        addAttr(){
          /*
            baseSaleAttrId:1
            saleAttrName:"选择颜色"
            spuId:210
            spuSaleAttrValueList:[
              {
                baseSaleAttrId:1
                isChecked:null
                saleAttrName:"选择颜色"
                saleAttrValueName:"123123123"
                spuId:209
              }
            ]
          */
          let [saleAttrName,baseSaleAttrId] = this.attr_id_name.split("-");
          let spuId = this.supInfo.id;
          let attr = {
            baseSaleAttrId,
            saleAttrName,
            spuId,
            spuSaleAttrValueList:[]
          };
          //将新生成的属性 加到 supInfo中
          this.supInfo.spuSaleAttrList.push(attr);
          //清空 attr_id_name
          this.attr_id_name = ""
        },

        //tag 相关
        showInput(row,index) {

          if(!row.hasOwnProperty("inputVisible")){
              this.$set(row,"inputVisible",true)
          }else{
              row.inputVisible = true
          }

          this.$nextTick( _ => {
            this.$refs[`saveTagInput${index}`].focus();
          });
        },
        handleInputConfirm(row,index) {
          //Dog1 ： 咬内容重复的逻辑
          let Dog1 = row.spuSaleAttrValueList.filter((item)=>{
              return item.saleAttrValueName === row.inputValue
          }).length >= 1;
          //Dog2 : 咬空的逻辑
          let Dog2 =  (row.inputValue === "" || row.inputValue === undefined)
          if(Dog2) return;

          //input隐藏  ； 按钮显示
          row.inputVisible = false;
          //构建一个属性值对象 将属性值对象塞入到属性对象中
          /*
            baseSaleAttrId:1
            saleAttrName:"选择颜色"
            saleAttrValueName:"123123123"
            spuId:209
          */
          const {baseSaleAttrId,saleAttrName,spuId} = row;
          let attrVal = {
            baseSaleAttrId,
            saleAttrName,
            saleAttrValueName:row.inputValue,
            spuId
          }
          row.spuSaleAttrValueList.push(attrVal);

          //清空输入框
          row.inputValue = ""

        },
        handleClose(row,index) {
          row.spuSaleAttrValueList.splice(index,1)
        }
      }
    }
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
